package com.fansz.FanszAPI.web;

import com.fansz.FanszAPI.common.BaseController;
import com.fansz.FanszAPI.common.unifystructre.UnifyResponse;
import com.fansz.FanszAPI.domain.Topic;
import com.fansz.FanszAPI.domain.TopicResponse;
import com.fansz.FanszAPI.domain.User;
import com.fansz.FanszAPI.service.BaseService;
import com.fansz.FanszAPI.service.UserService;
import com.fansz.FanszAPI.service.impl.TopicServiceImpl;
import com.fansz.FanszAPI.utils.Constants;
import com.fansz.FanszAPI.utils.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@Component
@RequestMapping("/topic")
public class TopicController extends BaseController {

    private static Logger logger = Logger.getLogger(TopicController.class);

    @Autowired
    TopicServiceImpl topicServiceImpl;

    @Autowired
    UserService userService;

    /**
     * 发贴接口
     * @param sessionId session
     * @param deviceId 客户端设备id
     * @param timeStamp 当前时间
     * @param content 话题内容
     * @param uid 用户ID
     * @param title 话题标题
     * @return resp 结果
     */
    @RequestMapping(value = "/submit", method = RequestMethod.POST, produces = "application/json")
    public UnifyResponse topicSubmit(@RequestParam(value = "sessionId", required = false) String sessionId,
                                     @RequestParam(value = "deviceId", required = false) String deviceId,
                                     @RequestParam(value = "timeStamp", required = false) String timeStamp,
                                     @RequestParam(value = "content", required = false) String content,
                                     @RequestParam(value = "uid", required = false) String uid,
                                     @RequestParam(value = "title", required = false) String title)
    {
        logger.info("-----[topicSubmit: Receive sessionId ： " + sessionId + ", deviceId : " + deviceId + ", timeStamp : " + timeStamp + ", content : " + content + ", uid : " + uid + ", title : " + title + "]-----");

        UnifyResponse resp = new UnifyResponse();

        try {
            //参数校验
            if (!topicSubmitParaCheck(sessionId, deviceId, timeStamp, content, uid, title))
            {
                resp = new UnifyResponse();
                resp.setCode(Constants.PARAM_CHECK_FAIL);
                resp.setInfo(Constants.PARAM_CHECK_FAIL_INFO);
                return resp;
            }

            boolean session = BaseService.containSession(sessionId);

            if (!session)
            {
                resp.setCode(Constants.SESSION_TIME_OUT);
                resp.setInfo(Constants.SESSION_TIME_OUT_INFO);
                return resp;
            }

            Topic topic = new Topic();

            topic.setUserId(uid);
            topic.setContent(content);
            topic.setTitle(title);
            String curTime = System.currentTimeMillis() + "";
            topic.setCreateTime(curTime);
            topic.setUpdateTime(curTime);

            topicServiceImpl.saveTopic(topic);

            Topic topicNew = topicServiceImpl.findByCreateTime(curTime);

            TopicResponse topicRes = getUserForTopic(topicNew);

            resp.setCode(Constants.SUCCESS_CODE);
            resp.setInfo(Constants.SUCCESS_INFO);
            resp.setContent(topicRes);
            logger.info("-----[topicSubmit response :" + resp.toString()  + "]-----");
        }
        catch (Exception e)
        {
            logger.error("topicSubmit error：" + e.getMessage());
            resp = new UnifyResponse();
            resp.setCode(Constants.SERVER_ERROR);
            resp.setInfo(Constants.SERVER_ERROR_INFO);
            return resp;
        }
        return resp;
    }

    /**
     * 为topic对象获取用户对象
     */
    private TopicResponse getUserForTopic(Topic topic)
    {
        TopicResponse topicRes = new TopicResponse();

        topicRes.setTitle(topic.getTitle());
        topicRes.setContent(topic.getContent());
        topicRes.setUser(userService.findByUserId(topic.getUserId()));
        topicRes.setId(topic.getId());
        topicRes.setCreateTime(topic.getCreateTime());
        topicRes.setUpdateTime(topic.getUpdateTime());

        return topicRes;
    }

    /**
     *
     * 发贴接口参数验证
     */
    private boolean topicSubmitParaCheck(String sessionId,String deviceId,String timeStamp,String content,String userId,String title)
    {
        boolean result = true;

        if (StringUtils.isEmpty(sessionId))
        {
            result = false;
        }
        else if (StringUtils.isEmptyAndLen(deviceId, Constants.deviceId))
        {
            result = false;
        }
        else if (StringUtils.isEmptyAndLen(timeStamp, Constants.timeStamp))
        {
            result = false;
        }
        else if (StringUtils.checkLen(content, Constants.topic_content))
        {
            result = false;
        }
        else if (StringUtils.isEmpty(userId))
        {
            result = false;
        }
        else if (StringUtils.checkLen(title, Constants.topic_title))
        {
            result = false;
        }

        return result;
    }

    /**
     * 发贴接口
     * @param sessionId session
     * @param deviceId 客户端设备id
     * @param timeStamp 当前时间
     * @param uid 用户ID
     * @param startTime 开始点
     * @param count 需要返回的topic数
     * @return resp 返回对象
     */
    @RequestMapping(value = "/search", method = RequestMethod.POST, produces = "application/json")
    public UnifyResponse searchByUser(@RequestParam(value = "sessionId", required = false) String sessionId,
                                      @RequestParam(value = "deviceId", required = false) String deviceId,
                                      @RequestParam(value = "timeStamp", required = false) String timeStamp,
                                      @RequestParam(value = "uid", required = false) String uid,
                                      @RequestParam(value = "startTime") String startTime,
                                      @RequestParam(value = "count", required = false) int count) {
        logger.info("-----[searchByUser: sessionId ： " + sessionId + ", deviceId : " + deviceId + ", timeStamp : " + timeStamp + ", uid : " + uid + ", startTime : " + startTime + ", count : " + count + "]-----");

        UnifyResponse resp = new UnifyResponse();

        try {
            //参数校验
            if (!searchParaCheck(sessionId, deviceId, timeStamp, uid, startTime, count))
            {
                resp = new UnifyResponse();
                resp.setCode(Constants.PARAM_CHECK_FAIL);
                resp.setInfo(Constants.PARAM_CHECK_FAIL_INFO);
                return resp;
            }

            boolean session = BaseService.containSession(sessionId);

            if (!session)
            {
                resp.setCode(Constants.SESSION_TIME_OUT);
                resp.setInfo(Constants.SESSION_TIME_OUT_INFO);
                return resp;
            }

            Topic topic = new Topic();

            List<Topic> topicList = topicServiceImpl.findByUser(uid, count, startTime);


            resp.setCode(Constants.SUCCESS_CODE);
            resp.setInfo(Constants.SUCCESS_INFO);
            resp.setContent(getUserForTopics(topicList));
            logger.info("-----[searchByUser response :" + resp.toString()  + "]-----");
        }
        catch (Exception e)
        {
            logger.error("searchByUser error：" + e.getMessage());
            resp = new UnifyResponse();
            resp.setCode(Constants.SERVER_ERROR);
            resp.setInfo(Constants.SERVER_ERROR_INFO);
            return resp;
        }

        return resp;
    }

    /**
     * 批量为topic对象获取用户对象
     */
    private List<TopicResponse> getUserForTopics(List<Topic> topicList)
    {
        List<TopicResponse> topicResponses = new ArrayList<TopicResponse>();

        if (topicList != null && topicList.size() > 0)
        {
            User user = null;
            for (Topic topic : topicList)
            {
                if (user == null)
                {
                    user = userService.findByUserId(topic.getUserId());
                }
                TopicResponse topicRes = new TopicResponse();

                topicRes.setTitle(topic.getTitle());
                topicRes.setContent(topic.getContent());
                topicRes.setUser(user);
                topicRes.setId(topic.getId());
                topicRes.setCreateTime(topic.getCreateTime());
                topicRes.setUpdateTime(topic.getUpdateTime());

                topicResponses.add(topicRes);
            }
        }

        return topicResponses;
    }

    /**
     *
     * 发贴接口参数验证
     */
    private boolean searchParaCheck(String sessionId,String deviceId,String timeStamp,String uid,String startTime,int topnum)
    {
        boolean result = true;

        if (StringUtils.isEmpty(sessionId))
        {
            result = false;
        }
        else if (StringUtils.isEmptyAndLen(deviceId, Constants.deviceId))
        {
            result = false;
        }
        else if (StringUtils.isEmptyAndLen(timeStamp, Constants.timeStamp))
        {
            result = false;
        }
        else if (StringUtils.isEmpty(uid))
        {
            result = false;
        }
        else if (StringUtils.isEmptyAndLen(startTime, Constants.timeStamp))
        {
            result = false;
        }
        else if (StringUtils.isEmptyAndLen(topnum + "", Constants.top_num))
        {
            result = false;
        }

        return result;
    }
}
